package com.example.voicechat

import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.concurrent.thread
import android.util.Log
import android.content.Context
import android.content.pm.PackageManager
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class AudioRecorder(private val context: Context) {
    private var audioRecord: AudioRecord? = null
    private var isRecording = AtomicBoolean(false)
    
    companion object {
        private const val SAMPLE_RATE = 16000
        private const val CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO
        private const val AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT
        private const val BUFFER_SIZE = 3200 // 增大缓冲区大小
    }
    
    fun startRecording(onData: (ByteArray) -> Unit) {
        if (isRecording.get()) {
            LogUtils.e("AudioRecorder", "录音已在进行中")
            return
        }
        
        // 确保录音权限
        if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.RECORD_AUDIO)
            != PackageManager.PERMISSION_GRANTED) {
            throw SecurityException("没有录音权限")
        }

        try {
            // 获取最小缓冲区大小
            val minBufferSize = AudioRecord.getMinBufferSize(
                SAMPLE_RATE,
                CHANNEL_CONFIG,
                AUDIO_FORMAT
            )

            // 使用较大的缓冲区大小
            val bufferSize = maxOf(minBufferSize, BUFFER_SIZE)
            LogUtils.e("AudioRecorder", "使用缓冲区大小: $bufferSize, 最小缓冲区: $minBufferSize")

            // 初始化AudioRecord
            audioRecord = AudioRecord(
                MediaRecorder.AudioSource.MIC,
                SAMPLE_RATE,
                CHANNEL_CONFIG,
                AUDIO_FORMAT,
                bufferSize
            )

            if (audioRecord?.state != AudioRecord.STATE_INITIALIZED) {
                LogUtils.e("AudioRecorder", "AudioRecord 初始化失败")
                audioRecord?.release()
                audioRecord = null
                return
            }

            isRecording.set(true)
            audioRecord?.startRecording()

            Thread {
                val buffer = ByteArray(bufferSize)
                while (isRecording.get()) {
                    val readSize = audioRecord?.read(buffer, 0, buffer.size) ?: 0
                    if (readSize > 0) {
                        LogUtils.e("AudioRecorder", "读取音频数据: $readSize bytes")
                        onData(buffer.copyOf(readSize))
                    } else {
                        LogUtils.e("AudioRecorder", "读取音频数据失败: $readSize")
                        break
                    }
                    Thread.sleep(20)  // 减少延迟
                }
                stopRecording()
            }.start()
            
            LogUtils.e("AudioRecorder", "录音已开始")
        } catch (e: Exception) {
            LogUtils.e("AudioRecorder", "录音初始化失败", e)
            stopRecording()
            throw RuntimeException("录音初始化失败: ${e.message}")
        }
    }
    
    fun stopRecording() {
        if (!isRecording.get()) {
            LogUtils.e("AudioRecorder", "录音已经停止")
            return
        }
        
        isRecording.set(false)
        try {
            audioRecord?.let { record ->
                if (record.state == AudioRecord.STATE_INITIALIZED) {
                    record.stop()
                }
                record.release()
            }
        } catch (e: Exception) {
            LogUtils.e("AudioRecorder", "停止录音时发生错误", e)
        } finally {
            audioRecord = null
        }
        LogUtils.e("AudioRecorder", "录音已停止")
    }
} 